//
//  ByUIIndexLocationVC.m
//  chequanbao_ios
//
//  Created by pro on 17/5/9.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIIndexLocationVC.h"


#import "BySearchBar.h"                 // 搜索框

// handle
#import "ByCoreAddressSqlite3.h"        //
#import "ByCoreToolLocation.h"          // 定位

// model
#import "ByModelLocationCity.h"

@interface ByUIIndexLocationVC () <UITableViewDelegate, UITableViewDataSource, ByCoreLoactionDelegate>

@property (nonatomic, strong) UIImageView *bgView;
@property (nonatomic, strong) UIView *searchBgView;
@property (nonatomic, strong) BySearchBar *searchBar;

@property (nonatomic, strong) UITableView *table;

@property (nonatomic, strong) NSArray *allCityModels;           // 所有城市的model数组
@property (nonatomic, strong) NSMutableDictionary *allCitysDic; // 键：AB..；值：字符串数组
@property (nonatomic, strong) NSArray *allCitys;                // 所有城市的字符串数组
@property (nonatomic, strong) NSArray *filterCitys;             // 筛选城市的字符串数组
@property (nonatomic, strong) NSArray *allKeys;                 // 所有键名


@end

@implementation ByUIIndexLocationVC

#pragma mark - view method
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"选择城市";
    
    [self addLeftBackBarButtonItem];
    
    [self performSelector:@selector(loading) withObject:nil afterDelay:0.01];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self initCityModels];
        dispatch_async(dispatch_get_main_queue(), ^{
            [ByCoreToolAlert hideHud];
            [self.table reloadData];
        });
    });
    
    [self createSearchBar];
    [self createTableView];
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self setNaviAttributeWithTranslucent:YES stateBarLightContent:YES];
}
- (void)loading {
    
    [ByCoreToolAlert showLoadind:@"正在加载..."];
}
#pragma mark - 懒加载
- (UIView *)searchBgView {
    
    if (!_searchBgView) {
        _searchBgView = [[UIView alloc] initWithFrame:CGRectMake(10, 64, SCREEN_WIDTH - 20, SCREEN_HEIGHT - 64)];
        _searchBgView.backgroundColor = [UIColor colorWithWhite:0.97 alpha:1];
        _searchBgView.layer.cornerRadius = 8;
        [self.view addSubview:_searchBgView];
    }
    return _searchBgView;
    
}
#pragma mark - build data
- (void)initCityModels {
    
    // 获取所有城市列表
    NSMutableArray *temp = [NSMutableArray new];
    NSArray *p_models = [ByCoreAddressSqlite3 getAllProvinceModel];
    for (ByCoreProvinceModel *p_model in p_models) {
        
        NSArray *c_models = [ByCoreAddressSqlite3 getAllCityModelWithProvinceID:p_model.provinceID];
        [temp addObjectsFromArray:c_models];
    }
    
    // 转换成包含首字母的城市列表
    NSMutableArray *temp2 = [NSMutableArray new];
    NSMutableArray *temp3 = [NSMutableArray new];
    for (ByCoreCityModel *c_model in temp) {
        ByModelLocationCity *cityModel = [[ByModelLocationCity alloc] initWithSuper:c_model];
        [temp2 addObject:cityModel];
        [temp3 addObject:cityModel.city];
    }
    self.allCityModels = temp2.copy;
    self.allCitys = temp3.copy;

    NSArray *ignoreCitys = @[@"县",
                             @"市",
                             @"市辖区",
                             @"省直辖行政单位",
                             @"省直辖县级行政单位",];
    
    // 组合相同字母的一组中
    NSMutableDictionary *dic = [NSMutableDictionary new];
    for (ByModelLocationCity *cityModel in self.allCityModels) {
        
        if ([ignoreCitys containsObject:cityModel.city]) {
            continue;
        }
        
        NSString *str = cityModel.firstLetter;
        if ([dic.allKeys containsObject:str]) {
            NSMutableArray *section = dic[str];
            [section addObject:cityModel.city];
        } else {
            NSMutableArray *section = [NSMutableArray new];
            [section addObject:cityModel.city];
            [dic setObject:section forKey:str];
        }
    }
    
    self.allCitysDic = dic.mutableCopy;
    
    // 获得交换键名后的数组
    self.allKeys = [self.allCitysDic.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString *key1, NSString *key2) {
        
        if ([key1 compare:key2] == NSOrderedAscending) {
            return NSOrderedAscending;
        } else {
            return NSOrderedDescending;
        }
    }];
}


#pragma mark - create views
- (void)createSearchBar {
    
    BySearchBar *searchbar = [[BySearchBar alloc] initWithFrame:CGRectMake(10, 10, self.searchBgView.width - 20, 30)];
    searchbar.searchBar.placeholder = @"请输入城市名";
    [self.searchBgView addSubview:self.searchBar = searchbar];
    searchbar.textDidChange = ^ (NSString *text) {
        if (text.length == 0){
            
            self.filterCitys = nil;
            [self.table reloadData];
        }
        else {
            // 返回包含searchText的所有的元素 谓词搜索
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self BEGINSWITH     %@", text];
            self.filterCitys = [self.allCitys filteredArrayUsingPredicate:predicate].copy;
            [self.table reloadData];
        }
    };
    
}

// 创建表视图
- (void)createTableView {
    
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, self.searchBar.bottom, self.searchBgView.width, self.searchBgView.height - self.searchBar.bottom) style:UITableViewStylePlain];
    self.table.backgroundColor = [UIColor clearColor];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.searchBgView addSubview:self.table];
    self.table.tableFooterView = [UIView new];
    self.table.sectionIndexBackgroundColor = [UIColor clearColor];
}

#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.filterCitys) {
        return 1 + 1;
    } else {
        return self.allKeys.count + 1;
    }
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else {
        if (self.filterCitys) {
            return self.filterCitys.count;
        } else {
            NSString *key = self.allKeys[section - 1];
            NSMutableArray *citys = self.allCitysDic[key];
            
            return citys.count;
        }
    }
    
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.textLabel.font = FONT(16);
        cell.textLabel.textColor = [UIColor blackColor];
    }
    
    if (indexPath.section == 0) {
        NSString *locationCity = BY_APPDELEGATE.locationCity;
        if (locationCity.length != 0) {
            cell.textLabel.text = locationCity;
        } else {
            cell.textLabel.text = @"点击定位";
        }
    } else {
        if (self.filterCitys) {
            cell.textLabel.text = self.filterCitys[indexPath.row];
        } else {
            NSString *key = self.allKeys[indexPath.section - 1];
            NSMutableArray *citys = self.allCitysDic[key];
            NSString *city = citys[indexPath.row];
            cell.textLabel.text = city;
        }
    }
    
    
    return cell;
    
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}
// 设置组头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 30;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UILabel *label = [[UILabel alloc] init];
    label.backgroundColor = self.searchBgView.backgroundColor;
    label.font = FONT(16);
    label.textColor = [UIColor blackColor];
    label.textAlignment = NSTextAlignmentLeft;
    
    if (section == 0) {
        label.text = @"    定位城市";
    } else {
        if (self.filterCitys) {
            label.text = @"    搜索结果";
        } else {
            label.text = [NSString stringWithFormat:@"    %@", self.allKeys[section - 1]];
        }
    }
    return label;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    
    if (self.filterCitys) {
        return nil;
    } else {
        NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:self.allKeys];
        [temp insertObject:@"" atIndex:0];
        return temp.copy;
    }
}

// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if (indexPath.section == 0) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if ([cell.textLabel.text isEqualToString:@"点击定位"]) {
            [self location];
        } else {
            ByModelLocationCity *cityModel = [self getCityModelWithCity:BY_APPDELEGATE.locationCity];
            if (self.locationDidSelected) {
                self.locationDidSelected(cityModel);
            }
        }
    }
    else {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSString *city = cell.textLabel.text;
        ByModelLocationCity *cityModel = [self getCityModelWithCity:city];
        if (self.locationDidSelected) {
            self.locationDidSelected(cityModel);
        }
    }
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - 定位ck
- (void)location {
    
    [ByCoreToolAlert showLoadind:@"正在定位..."];
    ByCoreToolLocation *locationManager = [ByCoreToolLocation shareInstance];
    locationManager.delegate = self;
    [locationManager configLocationService];
    [locationManager startUpdateLoaction];
}
- (void)locationDidComplete:(NSDictionary *)placeInfoDic {
    
    [ByCoreToolAlert hideHud];
    
    // 更新当前显示的城市
    
    // 设置定位城市
    BY_APPDELEGATE.locationCity = placeInfoDic[@"city"];
    
    [self.table reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
    
}
- (void)locationDidFail:(NSError *)error {
    [ByCoreToolAlert showOnlyText:@"定位失败"];
}




#pragma mark - util
// 根据城市中文名，获得城市model
- (ByModelLocationCity *)getCityModelWithCity:(NSString *)citystr {
    ByModelLocationCity *cityModel;
    for (ByModelLocationCity *model in self.allCityModels) {
        if ([citystr isEqualToString:model.city]) {
            cityModel = model;
            break;
        }
    }
    
    return cityModel;
    
}



@end
